<template>
  <transition name="fade" v-if="show">
    <div class="scan-main">
      <video ref="videoRef" v-if="!code"></video>
      <div v-else class="scan-success">
        <el-result icon="success" title="扫码成功" />
      </div>
    </div>
  </transition>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      show: false,
      code: '',
    }
  },
  computed: {},

  methods: {
    reset() {
      this.code = ''
    },
    start(options = {}) {
      let self = this
      this.reset()
      this.show = true
      this.$nextTick(() => {
        let opts = {
          continuous: true,
          video: this.$refs['videoRef'],
          mirror: false,
          captureImage: false,
          backgroundScan: true,
          refractoryPeriod: 5000,
          scanPeriod: 1,
          ...options,
        }
        let scanner = new Instascan.Scanner(opts)
        scanner.addListener('scan', (code) => {
          scanner.stop()
          scanner = null
          self.code = code
          // 只提交一次 防止触发多次
          self.$emit('code', code)
          self.$off('code')

          setTimeout(() => {
            self.show = false
          }, 300)
        })

        Instascan.Camera.getCameras()
          .then((cameras) => {
            if (cameras.length > 0) {
              scanner.start(cameras[0])
            } else {
              self.$message({ type: 'warning', message: '未发现摄像头' })
            }
          })
          .catch((e) => {
            console.log(`e ==>`,e);
            self.$message({ type: 'error', message: '该网站不支持' })
            self.show = false
          })
      })
    },
  },
}
</script>
<style scoped lang="scss">
.scan-main {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 1);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  outline: none;
  width: 100%;
  height: 100%;
  video {
    object-fit: cover;
    width: 300px;
    height: 300px;
  }
  .scan-success {
    width: 200px;
    height: 200px;
    border-radius: 5px;
    background: #efeeee;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
